package com.codewsq.java1;

import com.codewsq.entity.MyAnnotation;
import com.codewsq.entity.Person;
import org.junit.Test;

import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * 反射获取操作父类、接口
 */
public class SuperClassTest {


    /*
     * 获取运行时类的父类
     * */
    @Test
    public void test() {
        Class<Person> clazz = Person.class;
        Class<? super Person> superclass = clazz.getSuperclass();
        System.out.println(superclass);
    }

    /*
     * 获取运行时类的带泛型的父类
     * */
    @Test
    public void test2() {
        Class<Person> clazz = Person.class;
        Type superclass = clazz.getGenericSuperclass();
        System.out.println(superclass);
        String typeName = superclass.getTypeName();
        System.out.println(typeName);
    }

    /*
     * 获取运行时类的带泛型的父类的泛型
     * */
    @Test
    public void test3() {
        Class<Person> clazz = Person.class;
        Type genericSuperclass = clazz.getGenericSuperclass();
        ParameterizedType paramType = (ParameterizedType) genericSuperclass;
        // 获取泛型类型,因为泛型可能有多个，所以是数组
        Type[] actualTypeArguments = paramType.getActualTypeArguments();
        for (Type actualTypeArgument : actualTypeArguments) {
            System.out.println(actualTypeArgument);
        }
    }

    /*
     * 获取运行时类实现的接口interface
     * */
    @Test
    public void test4() {
        Class<Person> clazz = Person.class;
        Class<?>[] interfaces = clazz.getInterfaces();
        for (Class<?> anInterface : interfaces) {
            System.out.println(anInterface);
        }
        System.out.println("-------------------父类实现的接口--------------------------");
        // 获取运行时类父类实现的接口
        Class<?>[] interfaces1 = clazz.getSuperclass().getInterfaces();
        for (Class<?> aClass : interfaces1) {
            System.out.println(aClass);
        }
    }

    /*
     * 获取运行时类所在的包
     * */
    @Test
    public void test5() {
        Class<Person> clazz = Person.class;
        Package clazzPackage = clazz.getPackage();
        System.out.println(clazzPackage);
    }

    /*
     * 获取运行时类声明的注解
     * */
    @Test
    public void test6() {
        Class clazz = Person.class;
        Annotation[] annotations = clazz.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation.annotationType().getName());
            if ("com.codewsq.entity.MyAnnotation".equals(annotation.annotationType().getName())) {
                MyAnnotation myAnnotation = (MyAnnotation) annotation;
                System.out.println(myAnnotation.value()); // 获取注解的值
            }
        }
    }
}
